import axios from 'axios';
import './NurseScheduling.css'
import { useState, useEffect } from 'react';

function Scheduling() {
    const [dayLine, setDayLine] = useState([]);
    const [doctorId, setDoctorId] = useState(65);
    const [isLoading, setIsLoading] = useState(false);
    const [errorMessage, setErrorMessage] = useState(null);
    // 科室
    const [department, setDepartment] = useState('');
    // 头像
    const [avatar, setAvatar] = useState('');
    useEffect(() => {
        // 从本地存储中获取id
        const id = localStorage.getItem('dr_id');
        if (id) {
            setDoctorId(id);
        }
    }, []);

    useEffect(() => {
        axios.get(`http://8.148.7.123:8000/doctor/get_dn_dayline?id=${doctorId}`).then(res => {
            setDayLine(JSON.parse(res.data.data[0].date));
            setDepartment(res.data.data[0].department);
            setAvatar(`http://8.148.7.123:8000/images/headers/${res.data.data[0].head}`);
        }).catch(error => {
            console.log(error);
        });
    }, [doctorId]);

    const getWeekday = (dateStr) => {
        const date = new Date(dateStr);
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        return weekdays[date.getDay()];
    };

    const formatDate = (dateStr) => {
        const date = new Date(dateStr);
        return `${date.getMonth() + 1}/${date.getDate()}`;
    };

    const isEvenDay = (dateStr) => {
        const date = new Date(dateStr);
        return date.getDate() % 2 === 0;
    };

    const handlePeriodClick = async (date, period) => {
        if (isLoading) return;

        const newDayLine = dayLine.map(day => {
            if (day.date === date) {
                return {
                    ...day,
                    [period]: day[period] === 1 ? 0 : 1
                };
            }
            return day;
        });

        setDayLine(newDayLine);
        setIsLoading(true);
        setErrorMessage(null);
        // console.log(doctorId,JSON.stringify(newDayLine));
        const newDataStr = JSON.stringify(newDayLine).replace(/"/g, '\\"');
        try {
            await axios.post('http://8.148.7.123:8000/doctor/edit_dn_dayline', {
                id: doctorId,
                newdate: newDataStr
            });
        } catch (error) {
            setDayLine(dayLine); 
            if (axios.isAxiosError(error) && error.message === 'Network Error') {
                setErrorMessage('网络错误，请检查您的互联网连接并重试。');
            } else {
                setErrorMessage('更新排班时出错，请稍后重试。');
            }
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="SchedulingBox">
            <div className='SchedulingHeader'>
                <div className='SchedulingHeaderAvatar'>
                    <img className='SchedulingHeaderAvatarImg' src={avatar} alt="" />
                </div>
                <div className='SchedulingHeaderText'>科室：{department}</div>
            </div>
            <div className="SchedulingContent">
                {dayLine.map((item) => (
                    <div 
                        className={`SchedulingContentItem ${isEvenDay(item.date) ? 'even' : 'odd'}`} 
                        key={item.date}
                    >
                        <div className="SchedulingContentItemTime">
                            {formatDate(item.date)} 周{getWeekday(item.date)}
                        </div>
                        <div 
                            className={`SchedulingContentItemPeriod ${item.morning === 1 ? 'active' : ''} ${isLoading ? 'disabled' : ''}`}
                            onClick={() => handlePeriodClick(item.date, 'morning')}
                        >
                            上午
                        </div>
                        <div 
                            className={`SchedulingContentItemPeriod ${item.afternoon === 1 ? 'active' : ''} ${isLoading ? 'disabled' : ''}`}
                            onClick={() => handlePeriodClick(item.date, 'afternoon')}
                        >
                            下午
                        </div>
                        <div 
                            className={`SchedulingContentItemPeriod ${item.night === 1 ? 'active' : ''} ${isLoading ? 'disabled' : ''}`}
                            onClick={() => handlePeriodClick(item.date, 'night')}
                        >
                            夜班
                        </div>
                    </div>
                ))}
            </div>
            <div className="SchedulingFooter">
                {errorMessage && <div className="ErrorMessage">{errorMessage}</div>}
                <button className="SchedulingButton" disabled={isLoading}>
                    {isLoading ? '更新中...' : '修改排班'}
                </button>
            </div>
        </div>
    );
}

export default Scheduling;

